package service

import (
	"context"
	"gitee.com/kristas/booting-go/framework"
	"gitee.com/kristas/booting-go/framework/core/log"
	"gitee.com/kristas/booting-go/framework/core/statement"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
	"gitee.com/kristas/booting-go/framework/web/resp"
	"gitee.com/kristas/booting-go/internal/demo/dto"
	"gitee.com/kristas/booting-go/internal/demo/repository"
)

func init() {
	framework.Component(new(AccountServiceImpl))
}

type AccountService interface {
	statement.Service
	GetUserById(ctx context.Context, username string) (*dto.AccountDTO, error)
	GetAllUsers(ctx context.Context) ([]*dto.AccountDTO, error)
	SaveUser(ctx context.Context, username string, account *dto.AccountDTO) (resp.Response, error)
}

type AccountServiceImpl struct {
	types.Service      `service:"AccountService"`
	Log                log.Logger `wire:""`
	repository.Factory `wire:"repository_factory"`
}

func (r *AccountServiceImpl) GetUserById(ctx context.Context, username string) (*dto.AccountDTO, error) {
	account, err := r.GetAccountRepo().GetByUserName(ctx, username)
	if err != nil {
		return nil, resp.ErrInternalError(err)
	}
	return dto.NewAccountDTO(account), nil
}

func (r *AccountServiceImpl) GetAllUsers(ctx context.Context) ([]*dto.AccountDTO, error) {
	dtos := make([]*dto.AccountDTO, 0)
	list, err := r.GetAccountRepo().GetList(ctx)
	if err != nil {
		r.Log.Context(ctx).Error("GetAccountRepo.GetList: %s", err)
		return nil, resp.ErrInternalError(err)
	}
	r.Log.Context(ctx).Debug("GetAccountRepo.GetList: %d", len(list))
	for _, account := range list {
		dtos = append(dtos, dto.NewAccountDTO(account))
	}
	return dtos, nil
}

func (r *AccountServiceImpl) SaveUser(ctx context.Context, username string, account *dto.AccountDTO) (resp.Response, error) {
	if username != account.Username {
		return nil, resp.ErrBadRequest("username not matched.")
	}
	update, err := r.GetAccountRepo().Update(ctx, account.ToAccountModel())
	if err != nil {
		return nil, resp.ErrInternalError(err)
	}
	return resp.Created(dto.NewAccountDTO(update)), nil
}
